package com.itboye.ihomebank.activity.me;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidkun.breakpoints.event.DownloadData;
import com.androidkun.breakpoints.event.EventMessage;
import com.androidkun.breakpoints.utils.DownloadUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.itboye.ihomebank.R;

import com.itboye.ihomebank.base.NewBaseActivity;
import com.itboye.ihomebank.custom.RxRoundProgress;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DownloadApkListener;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.breakpoint_download.Download;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 更新
 */
public class UpdateActivity extends NewBaseActivity {
    TextView jindu,controlTv,bt;
    ImageView ivGif;
    String apkUrl;
    Download download;
    String version;//版本号
    boolean isDownload;
    /* 下载包安装路径 */
    /**
     * 文件保存路径
     */
    public final static String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/downloads/";
    private static final String savePath = "/sdcard/zhujia/";
    private static final String saveFileName = savePath
            + "zhujia.apk";
    /* 进度条与通知ui刷新的handler和msg常量 */
    private RxRoundProgress mProgress;

    @Override
    protected int layout_id() {
        return R.layout.activity_update;
    }

    @Override
    protected void onInitController() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Activity销毁时，取消网络请求
        OkGo.getInstance().cancelTag(this);
        EventBus.getDefault().unregister(this);
    }
    @Subscribe
    @Override
    public void onInit() {
        //  mProgress = (RxRoundProgress) findViewById(R.id.roundProgressBar1);
        apkUrl = getIntent().getStringExtra("url");
        ivGif = (ImageView) findViewById(R.id.ivGif);
        version = getIntent().getStringExtra("banbenhao");
        controlTv.setText("暂停");
        controlTv.setVisibility(View.VISIBLE);
        EventBus.getDefault().register(this);

//        Log.d("apkurl====",apkUrl);

        if (apkUrl!=null){
            isDownload=true;
            Glide.with(UpdateActivity.this).load(R.drawable.xiazaijindu).asGif().fitCenter()
                    .diskCacheStrategy(DiskCacheStrategy.ALL).into(ivGif);
            DownloadUtils.downLoad(this, apkUrl, downLoadPath,"zhujia.apk",1);
        }
//        if (apkUrl!=null){
//            Glide.with(UpdateActivity.this).load(R.drawable.xiazaijindu)
//                    .diskCacheStrategy(DiskCacheStrategy.ALL).into(ivGif);
//            getFile(apkUrl, getDiskFileDir(this) + File.separator + "/sdcard/zhujia/", "zhujia.apk");
//        }





    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMessage(EventMessage eventMessage) {
        switch (eventMessage.getType()){
            case EventMessage.TYPE_START://开始下载
                DownloadData progress = (DownloadData) eventMessage.getObject();
                jindu.setText(progress.getProgress() + "%");
                break;
            case EventMessage.TYPE_PROGRESS://下载
                DownloadData progress1 = (DownloadData) eventMessage.getObject();
                jindu.setText(progress1.getProgress() + "%");
                break;
            case EventMessage.TYPE_FINISHED://下载完成
                File file = new File(downLoadPath + "zhujia.apk");
                jindu.setText(100 + "%");
                if (file.exists()){
                      installapk(file);
                        }
               break;
            case EventMessage.TYPE_ERROR://下载失败
                DownloadData progress2 = (DownloadData) eventMessage.getObject();
                jindu.setText(progress2.getProgress() + "%");
                ByAlert.alert("下载失败");
                break;
            case EventMessage.TYPE_PAUSE://下载失败 (暂停
                DownloadData progress3 = (DownloadData) eventMessage.getObject();
                jindu.setText(progress3.getProgress() + "%");
                break;
        }
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.controlTv:
            if (isDownload){
                controlTv.setText("继续下载");
                DownloadUtils.pauseDownLoad(this, apkUrl);
                ivGif.setImageDrawable(UpdateActivity.this.getResources().getDrawable(R.drawable.xiazaijindu));
                isDownload=false;

            }else {
                controlTv.setText("暂停");
                DownloadUtils.downLoad(this, apkUrl, downLoadPath, "zhujia.apk", 1);
                isDownload=true;
                Glide.with(UpdateActivity.this).load(R.drawable.xiazaijindu).asGif().fitCenter()
                                .diskCacheStrategy(DiskCacheStrategy.ALL).into(ivGif);
            }
                break;
        }
    }

    /**
     * 下载APK
     * @param url
     * @param filePath
     * @param name
     */
    public void getFile(String url, final String filePath, String name) {
        OkGo.get(url)//
                .tag(this)//
                .execute(new FileCallback(filePath, name) {  //文件下载时，可以指定下载的文件目录和文件名
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        // file 即为文件数据，文件保存在指定目录
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
                        startActivity(i);
                    }
                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        //这里回调下载进度(该回调在主线程,可以直接更新ui)
                        int percent = (int) ((float) progress * 100);
                        jindu.setText(percent + "%");
//                        mProgress. setProgress((double) progress * 100);
                        System.out.println("进度：" + progress);
                    }
                });
    }


    /**
     * 获取缓存文件目录
     * @param context
     * @return
     */
    public static String getDiskFileDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
//            cachePath = context.getExternalCacheDir()
            cachePath = context.getExternalFilesDir(Environment.DIRECTORY_MOVIES).getPath();
        } else {
            cachePath = context.getFilesDir().getPath();
        }
        return cachePath;
    }
    /**
     * 安装apk
     * @param file
     */
    private void installapk(File file) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
        Log.d("download--",file.getAbsolutePath()+"");
        startActivity(i);
        this.finish();
    }

}
